import {NativeModules,NativeEventEmitter, Platform} from 'react-native'
let AMapGeoSearch = NativeModules.AMapGeoSearch;
let eventEmitter = new NativeEventEmitter(AMapGeoSearch);
const FitCityName = (location)=>{
    if(location.city == '' && location.district !='')
    {
        return {...location ,city:location.district,district:''}
    }
    return location
}
class TaskQueue{

    queue = []
    execting = false
    currentTask = null
    addTask(location,callback)
    {
        if(this.execting)
        {
            this.queue.push({data:location,cb:callback})
        }
        else{
            this.currentTask = {data:location,cb:callback}
            this.execte(location)
        }
    }
    getNextTask()
    {
        if(this.execting)
        {
            this.execting = false 
        }
        const task = this.queue.shift()
        return task
    }
    execte(location)
    {
        this.execting = true
        AMapGeoSearch.reGeocodeSearch(location)
    }
    listener(location)
    {
      if(this.currentTask)
      {
        const cb =  this.currentTask?.cb 
        const la = FitCityName(location)
        cb&&cb(la)
      }
       const task =  this.getNextTask()
       if(task)
       {
           this.currentTask = task
           this.execte(task.data)
       }
       else{
        this.currentTask = null
       }
    }
}
class GeoSearch{
  
    static taskQueue = new TaskQueue()
    static init(keys)
    {
        const key = Platform.OS == 'ios' ? keys.ios : keys.android
        AMapGeoSearch.init(key)
        eventEmitter.addListener("AMapReGeocodeSearch", (locations)=>{
            this.taskQueue.listener(locations)
        });
    }
    static  reGeocodeSearch(location,callback)
    {
        this.taskQueue.addTask(location,callback)
    }
 
    static  searchPOI(location,callback)
    {

        AMapGeoSearch.searchPOI(location)
        eventEmitter.removeAllListeners('AMapGeoSearch')
        eventEmitter.addListener("AMapGeoSearch", (locations)=>{
            callback&& callback(locations)
        });
    }
    static  searchPOIkeyWord(location,callback)
    {

        AMapGeoSearch.searchPOIkeyWord(location)
        eventEmitter.removeAllListeners('AMapGeoSearch')
        eventEmitter.addListener("AMapGeoSearch", (locations)=>{
            callback&& callback(locations)
        });
    }
    static showRoute(params,callback)
    {
        
        AMapGeoSearch.showRoute(params)
        eventEmitter.removeAllListeners('AMapRouteSearch')
        eventEmitter.addListener("AMapRouteSearch", (poly)=>{
            callback&& callback(poly)
        });
    }
  
}

export default  GeoSearch
